# coding: utf-8

class Allen(object):
    BEFORE = 0
    MEETS = 1
    OVERLAPS = 2
    STARTS_WITH = 3
    DURING = 4
    FINISHES_WITH = 5
    EQUALS = 6

    relation_names = (
        'before',
        'meets',
        'overlaps',
        'starts-with',
        'during',
        'finishes-with',
        'equals',
    )

    def __init__(self, rel, prop1, prop2, inv=False):
        self.rel = rel
        self.prop1 = prop1
        self.prop2 = prop2
        self.inv = inv

    def __eq__(self, other):
        return ((self.rel, self.prop1, self.prop2, self.inv) ==
                (other.rel, other.prop1, other.prop2, other.inv))

    def __str__(self):
        return '(%s %s%s %s)' % (self.prop1,
                                 '!' if self.inv else '',
                                 self.relation_names[self.rel],
                                 self.prop2)
                                               
    def __repr__(self):
        return '<Allen %s>' % self
       
    @classmethod 
    def from_fluents(cls, f1, f2):
        if f1.start == f2.start and f1.end == f2.end:
            return cls(cls.EQUALS, f1.prop, f2.prop)

        elif f1.start == f2.start:
            return cls(cls.STARTS_WITH, f1.prop, f2.prop)

        elif f1.end == f2.end:
            return cls(cls.FINISHES_WITH, f1.prop, f2.prop)

        elif f1.end == f2.start:
            return cls(cls.MEETS, f1.prop, f2.prop)

        elif f1.end < f2.start:
            return cls(cls.BEFORE, f1.prop, f2.prop)

        elif f1.start > f2.start and f1.end < f2.end:
            return cls(cls.DURING, f1.prop, f2.prop)

        elif f1.start < f2.start and f1.end > f2.start and f1.end < f2.end:
            return cls(cls.OVERLAPS, f1.prop, f2.prop)
            
    def inverse(self):
        return Allen(self.rel, self.prop2, self.prop1, inv=(not self.inv))
